package com.nuoniu.sibanyun.service.finance.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.dto.AccountingVoucherDto;
import com.nuoniu.sibanyun.entity.erp.ErpAccount;
import com.nuoniu.sibanyun.entity.erp.ErpPeriod;
import com.nuoniu.sibanyun.entity.finance.*;
import com.nuoniu.sibanyun.entity.inOut.VInOutRecordMain;
import com.nuoniu.sibanyun.mapper.finance.VAccountingAuxiliaryLedgerMapper;
import com.nuoniu.sibanyun.mapper.finance.VAccountingVoucherMainMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.erp.IErpPeriodService;
import com.nuoniu.sibanyun.service.finance.*;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * <p>
 * 会计凭证主表 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2021-04-09
 */
@Service
public class VAccountingVoucherMainServiceImpl extends ServiceImpl<VAccountingVoucherMainMapper, VAccountingVoucherMain> implements IVAccountingVoucherMainService {

    @Autowired
    private IErpAccountService accountService;
    @Autowired
    private IVAccountingVoucherDetailService accountingVoucherDetailService;
    @Autowired
    @Lazy
    private IVAccountingLedgerService accountingLedgerService;
    @Autowired
    private IErpPeriodService periodService;
    @Autowired
    @Lazy
    private VAccountingAuxiliaryLedgerMapper auxiliaryLedgerMapper;
    @Autowired
    private IVAssetsLiabilitiesMainService liabilitiesMainService;

    @Override
    public Page<VAccountingVoucherMain> pageList(Page page, AccountingVoucherDto accountingVoucher) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("company_id", userInfo.getCompanyId());
        if (StringUtils.isNotBlank(accountingVoucher.getBeginCode())) {
            wrapper.ge("code", accountingVoucher.getBeginCode());
        }
        if (StringUtils.isNotBlank(accountingVoucher.getEndCode())) {
            wrapper.le("code", accountingVoucher.getEndCode());
        }
        if (accountingVoucher.getReviewerDate() != null) {
            wrapper.eq("date(reviewer_date)", accountingVoucher.getReviewerDate());
        }
        if (accountingVoucher.getReviewerUserId() != null) {
            wrapper.eq("reviewer_user_id", accountingVoucher.getReviewerUserId());
        }
        if (StringUtils.isNotBlank(accountingVoucher.getBookDate())) {
            wrapper.eq("date(book_date)", accountingVoucher.getBookDate());
        }
        if (accountingVoucher.getBookkeeperId() != null) {
            wrapper.eq("bookkeeper_id", accountingVoucher.getBookkeeperId());
        }
        if (accountingVoucher.getStatus() != null) {
            wrapper.eq("status", accountingVoucher.getStatus());
        }
        if (accountingVoucher.getIsDelete() != null) {
            wrapper.eq("is_delete", accountingVoucher.getIsDelete());
        }
        if (StringUtils.isNotBlank(accountingVoucher.getCreateDate())) {
            wrapper.eq("date(create_date)", accountingVoucher.getCreateDate());
        }
        if (accountingVoucher.getBeginBusinessDate() != null) {
            wrapper.ge("date(business_date)", accountingVoucher.getBeginBusinessDate());
        }
        if (accountingVoucher.getEndBusinessDate() != null) {
            wrapper.le("date(business_date)", accountingVoucher.getEndBusinessDate());
        }
        if (StringUtils.isNotBlank(accountingVoucher.getYear())) {
            wrapper.eq("account_year", accountingVoucher.getYear());
        }
        if (StringUtils.isNotBlank(accountingVoucher.getBeginPeriod())) {
            wrapper.ge("account_period", accountingVoucher.getBeginPeriod());
        }
        if (StringUtils.isNotBlank(accountingVoucher.getEndPeriod())) {
            wrapper.le("account_period", accountingVoucher.getEndPeriod());
        }
        wrapper.orderByAsc("number");

        Page<VAccountingVoucherMain> main = page(page, wrapper);
        List<VAccountingVoucherMain> mainList = main.getRecords();
        mainList.forEach(m -> {
            VAccountingVoucherDetail detail = accountingVoucherDetailService.getManDetail(m.getId());
            m.setDescription(detail.getDescription());
//            m.setRemark(detail.getRemark());
            m.setCreditAmount(detail.getCreditAmount());
            m.setDebitAmount(detail.getDebitAmount());
        });
        return main;
    }

    @Override
    @Transactional
    public Long saveAccountingVoucher(VAccountingVoucherMain accountingVoucherMain) {
        UserInfo userInfo = UserThreadLocal.get();
        Integer accountId = accountService.getCurrentAccountId();
        ErpPeriod period = periodService.getByDate(accountingVoucherMain.getBusinessDate(), userInfo.getCompanyId(), accountId);
        if (period == null) {
            throw new NuoNiuException("未找到对应的期间！！！");
        }
        //zy新增
        LocalDate businessDate = accountingVoucherMain.getBusinessDate();
        int year = businessDate.getYear();
        int monthValue = businessDate.getMonthValue();
        ErpPeriod period1 = periodService.getByPeriod(year, monthValue);
        if (period1 != null) {
            if (period1.getFiTerminalState() != null && period1.getFiTerminalState().equals(1)) {
                throw new NuoNiuException("当前期间已财务结账");
            }
        }
//****************
        if (StringUtils.isBlank(accountingVoucherMain.getDescription())){
            throw new NuoNiuException("描述为空，请添加描述");
        }
        String code = accountingVoucherMain.getCode();
        VAccountingVoucherMain accountingByCode = baseMapper.checkCode(userInfo.getCompanyId(), period.getCurrentYear(), period.getCurrentPeriod(), code);
        if (accountingByCode != null && (accountingVoucherMain.getId() == null || !accountingByCode.getId().equals(accountingVoucherMain.getId()))) {
            throw new NuoNiuException("凭证号已存在,请修改后再保存");
        }

        accountingVoucherMain.setCode(code);
        accountingVoucherMain.setNumber(Integer.valueOf(code));
        if (accountingVoucherMain.getId() == null) {
            accountingVoucherMain.setCompanyId(userInfo.getCompanyId());
            accountingVoucherMain.setAccountId(accountId);
            accountingVoucherMain.setAccountYear(period.getCurrentYear());
            accountingVoucherMain.setAccountPeriod(period.getCurrentPeriod());
            accountingVoucherMain.setCreateUserId(userInfo.getUserId());
            accountingVoucherMain.setCreateUserName(userInfo.getRealName());
        } else {
            VAccountingVoucherMain voucherMain = this.getById(accountingVoucherMain.getId());
            if (!voucherMain.getStatus().equals(0)) {
                throw new NuoNiuException("未审状态下才能修改");
            }

            //获取当前期间已记账最大编号
            Integer number = baseMapper.getBookMaxCode(accountingVoucherMain.getCompanyId(), accountingVoucherMain.getAccountYear(), accountingVoucherMain.getAccountPeriod());
            if (number != null && Integer.valueOf(voucherMain.getNumber()) <= number && !voucherMain.getNumber().equals(accountingVoucherMain.getNumber())) {
                throw new NuoNiuException("当前凭证号小于最大记账凭证编号,不能修改");
            }

            accountingVoucherMain.setUpdateDate(LocalDate.now());
            accountingVoucherMain.setUpdateUserId(userInfo.getUserId());
            accountingVoucherMain.setUpdateUserName(userInfo.getRealName());
        }

        //保存会计凭证
        saveOrUpdate(accountingVoucherMain);

        //保存明细
        List<Long> detailIds = new ArrayList<>();
        BigDecimal decimalAmount = new BigDecimal(0.0);
        BigDecimal creditAmount = new BigDecimal(0.0);
        accountingVoucherMain.getAccountingVoucherDetails().forEach(a -> {
            if (a.getDebitAmount() == null && a.getCreditAmount() == null) {
                throw new NuoNiuException("借贷方不能同时为空");
            }

            if (a.getDebitAmount() != null && a.getDebitAmount().compareTo(BigDecimal.ZERO) != 0
                    && a.getCreditAmount() != null && a.getDebitAmount().compareTo(BigDecimal.ZERO) != 0) {
                throw new NuoNiuException("借贷方不能同时有数据");
            }

            if (a.getDebitAmount() != null && a.getDebitAmount().compareTo(BigDecimal.ZERO) != 0) {
                decimalAmount.add(a.getDebitAmount());
            } else {
                creditAmount.add((a.getCreditAmount()));
            }

            a.setOrderId(accountingVoucherMain.getId().intValue());
            a.setCompanyId(userInfo.getCompanyId());
            a.setAccountId(accountId);
            a.setAccountYear(period.getCurrentYear());
            a.setAccountPeriod(period.getCurrentPeriod());
            if (a.getId() != null) {
                detailIds.add(a.getId());
            }
        });

        if (decimalAmount.compareTo(creditAmount) != 0) {
            throw new NuoNiuException("借贷不平衡！借方合计是" + decimalAmount.doubleValue() + "，贷方合计是" + creditAmount.doubleValue());
        }

        //删除明细
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("company_id", userInfo.getCompanyId());
        wrapper.eq("order_id", accountingVoucherMain.getId());
        if (detailIds != null && detailIds.size() > 0) {
            wrapper.notIn("id", detailIds);
            accountingVoucherDetailService.remove(wrapper);
        } else {
            accountingVoucherDetailService.remove(wrapper);
        }

        accountingVoucherDetailService.saveOrUpdateBatch(accountingVoucherMain.getAccountingVoucherDetails());
        return accountingVoucherMain.getId();
//        //保存汇总
//        List<Long> summaryIds = new ArrayList<>();
//        accountingVoucherMain.getAccountingVoucherSummaries().forEach(a -> {
//            a.setOrderId(accountingVoucherMain.getId().intValue());
//            a.setCompanyId(userInfo.getCompanyId());
//            a.setAccountId(accountService.getCurrentAccountId());
//            if(a.getId() != null) {
//                summaryIds.add(a.getId());
//            }
//        });
//
//        //删除明细
//        QueryWrapper sWrapper = new QueryWrapper();
//        sWrapper.eq("company_id", userInfo.getCompanyId());
//        sWrapper.eq("order_id", accountingVoucherMain.getId());
//        if(detailIds != null && detailIds.size() > 0) {
//            sWrapper.notIn("id", summaryIds);
//            accountingVoucherSummaryService.remove(sWrapper);
//        }else {
//            accountingVoucherSummaryService.remove(sWrapper);
//        }
//        //保存汇总
//        accountingVoucherSummaryService.saveOrUpdateBatch(accountingVoucherMain.getAccountingVoucherSummaries());
    }

    @Override
    public Map<String, Object> examine(List<Long> ids, Integer status) {
        UserInfo userInfo = UserThreadLocal.get();
        Map<String, Object> resultMap = new HashMap<>();
        List<String> resultData = new ArrayList<>();
        for (int i = 0; i < ids.size(); i++) {
            VAccountingVoucherMain accountingVoucherMain = this.getById(ids.get(i));
            if (!userInfo.getCompanyId().equals(accountingVoucherMain.getCompanyId())) {
                throw new NuoNiuException("您没有此权限,请联系管理员");
            }
            if (accountingVoucherMain == null) {
                resultData.add("第" + (i + 1) + "条审核失败,原因: 会计凭证不存在");
                continue;
            }
            if (accountingVoucherMain.getStatus().equals(3)) {
                resultData.add("第" + (i + 1) + "条审核失败,原因: 已记账");
                continue;
            }
//        if(!accountingVoucherMain.getCreateUserId().equals(userInfo.getUserId())) {
//            throw new NuoNiuException("你没有权限审核该记录");
//        }
            if (status.equals(1)) {
                accountingVoucherMain.setStatus(status);
                accountingVoucherMain.setReviewerDate(LocalDate.now());
                accountingVoucherMain.setReviewerUserId(userInfo.getUserId());
                accountingVoucherMain.setReviewerUserName(userInfo.getRealName());
                updateById(accountingVoucherMain);
            } else {
                accountingVoucherMain.setStatus(status);
                accountingVoucherMain.setReviewerDate(null);
                accountingVoucherMain.setReviewerUserId(null);
                accountingVoucherMain.setReviewerUserName(null);
                baseMapper.updateAccountingStatus(accountingVoucherMain.getId());
            }
        }

        resultMap.put("result", resultData);
        resultMap.put("sCount", ids.size() - resultData.size());
        resultMap.put("fCount", resultData.size());
        return resultMap;
    }

    @Override
    @Transactional
    public void deleteById(Long id, Integer status) {
        UserInfo userInfo = UserThreadLocal.get();
        VAccountingVoucherMain accountingVoucherMain = getById(id);
        if (accountingVoucherMain == null || !userInfo.getCompanyId().equals(accountingVoucherMain.getCompanyId())) {
            throw new NuoNiuException("您没有此权限,请联系管理员");
        }
        if (!accountingVoucherMain.getStatus().equals(0)) {
            throw new NuoNiuException("已审核/记账,不能操作");
        }

        //获取当前期间已记账最大编号
        Integer number = baseMapper.getBookMaxCode(accountingVoucherMain.getCompanyId(), accountingVoucherMain.getAccountYear(), accountingVoucherMain.getAccountPeriod());
        if (number != null && Integer.valueOf(accountingVoucherMain.getNumber()) <= number) {
            throw new NuoNiuException("小于最大记账凭证编号,不能删除");
        }
        this.removeById(id);
    }

    @Override
    public VAccountingVoucherMain getOneByCondition(Integer actionType, Long currentId) {
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = accountService.getCurrentAccountId();
        VAccountingVoucherMain result = null;
        if (actionType != null) {
            switch (actionType) {
                case 2:
                    result = baseMapper.getNextId(userInfo.getCompanyId(), currentAccountId, currentId);
                    break;
                case 1:
                    result = baseMapper.getPreId(userInfo.getCompanyId(), currentAccountId, currentId);
                    break;
                case 3:
                    result = baseMapper.getFirstId(userInfo.getCompanyId(), currentAccountId);
                    break;
                case 4:
                    result = baseMapper.getLastId(userInfo.getCompanyId(), currentAccountId);
                    break;
                case 5:
                    result = this.getById(currentId);
                    break;
            }
        }
        if (result != null) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("order_id", result.getId());
            result.setAccountingVoucherDetails(accountingVoucherDetailService.list(wrapper));
        }
        return result;
    }

    @Override
    @Transactional
    public Map<String, Object> book(List<Long> ids) {
        UserInfo userInfo = UserThreadLocal.get();
        ErpAccount account = accountService.getLastErpAccount();
        Integer count = baseMapper.getBookCountByYear(userInfo.getCompanyId(), account.getAccountYear());
        if (count == 0) {
            checkTrialBalance();
        }

        Map<String, Object> resultMap = new HashMap<>();
        List<String> resultData = new ArrayList<>();
        List<VAccountingVoucherMain> voucherMains = new ArrayList<>();
        String aIds = "";

        for (int i = 0; i < ids.size(); i++) {
            VAccountingVoucherMain accountingVoucherMain = getById(ids.get(i));
            if (accountingVoucherMain == null) {
                continue;
            }

            if (!userInfo.getCompanyId().equals(accountingVoucherMain.getCompanyId())) {
                throw new NuoNiuException("您没有此权限,请联系管理员");
            }

            if (accountingVoucherMain.getIsDelete().equals(1)) {
                resultData.add(accountingVoucherMain.getClassWord() + "-" + accountingVoucherMain.getNumber() + "凭证记账失败,原因: 已废除");
                continue;
            }

            if (accountingVoucherMain.getStatus().equals(0)) {
                resultData.add(accountingVoucherMain.getClassWord() + "-" + accountingVoucherMain.getNumber() + "凭证记账失败,原因: 未审核");
                continue;
            }

            if (accountingVoucherMain.getStatus().equals(3)) {
                resultData.add(accountingVoucherMain.getClassWord() + "-" + accountingVoucherMain.getNumber() + "凭证记账失败,原因: 已记账");
                continue;
            }

            //判断之前凭证号是否连续
            Integer minNumber = baseMapper.getBookMinNumber(accountingVoucherMain);
            minNumber = minNumber != null ? minNumber : 1;
            Integer[] numberArr = baseMapper.getBookNumber(minNumber, accountingVoucherMain);
            String noNumber = "";
            for (int n = minNumber + 1; n < accountingVoucherMain.getNumber(); n++) {
                int a = 0;
                for (; a < numberArr.length; a++) {
                    if (numberArr[a].equals(n)) {
                        break;
                    }
                }
                if (a >= numberArr.length) {
                    noNumber += n + ",";
                }
            }
            if (noNumber.length() > 0) {
                resultData.add(accountingVoucherMain.getClassWord() + "-" + accountingVoucherMain.getNumber() + "凭证记账失败,原因: 凭证号不连续,请补齐凭证号为 " + noNumber + " 的凭证");
                continue;
            }
            //记账凭证
            accountingVoucherMain.setStatus(3);
            accountingVoucherMain.setBookDate(LocalDateTime.now());
            accountingVoucherMain.setBookkeeperName(userInfo.getRealName());
            accountingVoucherMain.setBookkeeperId(userInfo.getUserId());
            aIds += accountingVoucherMain.getId().toString();
            if (i + 1 < ids.size()) {
                aIds += ",";
            }
            voucherMains.add(accountingVoucherMain);
        }

        resultMap.put("result", resultData);
        resultMap.put("sCount", ids.size() - resultData.size());
        resultMap.put("fCount", resultData.size());
        if (voucherMains.size() == 0) {
            return resultMap;
        }

        updateBatchById(voucherMains);
        //accountingVoucherDetailService.updateStatus(aIds);
        //计入总账
        List<VAccountingVoucherDetail> voucherDetails = accountingVoucherDetailService.getAccountingAmount(aIds);
        accountingLedgerService.saveAccounting(voucherDetails);

        //重新计算公式
        liabilitiesMainService.newCountFormula(voucherDetails);

        if (account.getStatus() != 2) {
            account.setStatus(2);
            accountService.updateById(account);
        }

        return resultMap;
    }
//zy编写，将借贷变为负数，将日期删除；
    @Override
    public Map<String, Object> unBook(List<Long> ids) {
        UserInfo userInfo = UserThreadLocal.get();
        ErpAccount account = accountService.getLastErpAccount();
        Integer count = baseMapper.getBookCountByYear(userInfo.getCompanyId(), account.getAccountYear());
        if (count == 0) {
            checkTrialBalance();
        }

        Map<String, Object> resultMap = new HashMap<>();
        List<String> resultData = new ArrayList<>();
        List<VAccountingVoucherMain> voucherMains = new ArrayList<>();
        String aIds = "";

        for (int i = 0; i < ids.size(); i++) {
            VAccountingVoucherMain accountingVoucherMain = getById(ids.get(i));
            if (accountingVoucherMain == null) {
                continue;
            }

            if (!userInfo.getCompanyId().equals(accountingVoucherMain.getCompanyId())) {
                throw new NuoNiuException("您没有此权限,请联系管理员");
            }

            if (accountingVoucherMain.getIsDelete().equals(1)) {
                resultData.add(accountingVoucherMain.getClassWord() + "-" + accountingVoucherMain.getNumber() + "凭证记账失败,原因: 已废除");
                continue;
            }

            if (accountingVoucherMain.getStatus().equals(0)) {
                resultData.add(accountingVoucherMain.getClassWord() + "-" + accountingVoucherMain.getNumber() + "凭证记账失败,原因: 未审核");
                continue;
            }

//            if (accountingVoucherMain.getStatus().equals(3)) {
//                resultData.add(accountingVoucherMain.getClassWord() + "-" + accountingVoucherMain.getNumber() + "凭证记账失败,原因: 已记账");
//                continue;
//            }

            //判断之前凭证号是否连续
            Integer minNumber = baseMapper.getBookMinNumber(accountingVoucherMain);
            minNumber = minNumber != null ? minNumber : 1;
            Integer[] numberArr = baseMapper.getBookNumber(minNumber, accountingVoucherMain);
            String noNumber = "";
            for (int n = minNumber + 1; n < accountingVoucherMain.getNumber(); n++) {
                int a = 0;
                for (; a < numberArr.length; a++) {
                    if (numberArr[a].equals(n)) {
                        break;
                    }
                }
                if (a >= numberArr.length) {
                    noNumber += n + ",";
                }
            }
            if (noNumber.length() > 0) {
                resultData.add(accountingVoucherMain.getClassWord() + "-" + accountingVoucherMain.getNumber() + "凭证记账失败,原因: 凭证号不连续,请补齐凭证号为 " + noNumber + " 的凭证");
                continue;
            }
            //记账凭证
            accountingVoucherMain.setStatus(1);
            accountingVoucherMain.setBookDate(LocalDateTime.now());
            accountingVoucherMain.setBookkeeperName(userInfo.getRealName());
            accountingVoucherMain.setBookkeeperId(userInfo.getUserId());
            aIds += accountingVoucherMain.getId().toString();
            if (i + 1 < ids.size()) {
                aIds += ",";
            }
            voucherMains.add(accountingVoucherMain);
        }

        resultMap.put("result", resultData);
        resultMap.put("sCount", ids.size() - resultData.size());
        resultMap.put("fCount", resultData.size());
        if (voucherMains.size() == 0) {
            return resultMap;
        }

        updateBatchById(voucherMains);
        //accountingVoucherDetailService.updateStatus(aIds);
        //计入总账
        List<VAccountingVoucherDetail> voucherDetails = accountingVoucherDetailService.getAccountingAmount(aIds);
        List<VAccountingVoucherDetail> collect = voucherDetails.stream().map(voucherDetail -> {
            voucherDetail.setDebitAmount(voucherDetail.getDebitAmount().negate());
            voucherDetail.setCreditAmount(voucherDetail.getCreditAmount().negate());

            return voucherDetail;
        }).collect(Collectors.toList());
        accountingLedgerService.saveAccounting(collect);

        //重新计算公式
        liabilitiesMainService.newCountFormula(voucherDetails);

        if (account.getStatus() != 2) {
            account.setStatus(2);
            accountService.updateById(account);
        }

        return resultMap;
    }

    @Override
    public String getCode(LocalDate businessDate) {
        Integer accountId = accountService.getCurrentAccountId();
        String number = baseMapper.getNewest(accountId, businessDate);
        if (StringUtils.isBlank(number)) {
            return "1";
        }

        number = Integer.parseInt(number) + 1 + "";
        if (number.length() > 4) {
            throw new NuoNiuException("当前业务月份凭证数量已上限！！！");
        }

//        switch (number.length()) {
//            case 1: number = "000" + number; break;
//            case 2: number = "00" + number; break;
//            case 3: number = "0" + number; break;
//        }
        return number;
    }

    @Override
    public Integer getBookCount(Integer year, Integer month, Integer companyId) {
        return baseMapper.getBookCount(year, month, companyId);
    }

    //zy新增
    @Override
    public List<VInOutRecordMain> getBusinessCount(LocalDate beginDate, LocalDate endDate, Integer companyId) {
        return baseMapper.getBusinessCount(beginDate, endDate, companyId);
    }


    @Override
    public void collateAccounting(Integer accountPeriod) {
        ErpAccount account = accountService.getLastErpAccount();
        Integer maxNumber = baseMapper.getBookMaxCode(UserThreadLocal.get().getCompanyId(), account.getAccountYear(), accountPeriod);
        maxNumber = maxNumber != null ? maxNumber : 0;
        List<VAccountingVoucherMain> voucherMainList = baseMapper.getListByPeriod(accountPeriod, account.getAccountYear(), UserThreadLocal.get().getCompanyId(), maxNumber);
        for (VAccountingVoucherMain main : voucherMainList) {
            ++maxNumber;
            main.setNumber(maxNumber);
            main.setCode(maxNumber.toString());
        }
        this.updateBatchById(voucherMainList);
    }

    /**
     * 试算平衡
     *
     * @author 小啊刚
     * @date 2021-05-22
     */
    public void checkTrialBalance() {
        ErpAccount account = accountService.getLastErpAccount();
        UserInfo userInfo = UserThreadLocal.get();
        //获取科目辅助期初
        List<VAccountingAuxiliaryLedger> auxiliaryLedgers = auxiliaryLedgerMapper.getAuxiliaryLedgerList(userInfo.getCompanyId(), account.getAccountYear());
        for (VAccountingAuxiliaryLedger ledger : auxiliaryLedgers) {
            VAccountingLedger accountingLedger = accountingLedgerService.getById(ledger.getAccountingId(), account.getAccountYear(), 1);
            //期初对比
            if (accountingLedger.getBeginAmount().compareTo(ledger.getBeginAmount()) != 0) {
                throw new NuoNiuException("科目期初和辅助期初不平衡");
            }
        }
    }
}
